package org.infodavid.common.impl.tasks;

import java.io.Serializable;
import java.util.HashMap;
import java.util.Map;

import javax.ejb.TransactionAttribute;
import javax.ejb.TransactionAttributeType;
import javax.ejb.TransactionManagement;
import javax.ejb.TransactionManagementType;

import org.joda.time.DateTime;

import org.infodavid.common.persistence.UserSessionDataService;
import org.infodavid.common.scheduler.commands.IScheduledCommand;
import org.infodavid.common.services.IApplicationContext;
import org.infodavid.common.services.SchedulerService;
import org.infodavid.common.services.UserService;
import org.infodavid.common.util.IVisitor;

/**
 * The Class UserSessionsRemovalTask.
 */
@SuppressWarnings({
    "boxing", "unchecked", "rawtypes"
})
@TransactionManagement(TransactionManagementType.BEAN)
public class UserSessionsRemovalTask implements IVisitor<IScheduledCommand,Object> {

	/**
	 * Process.
	 * @param since the since
	 * @return true, if successful
	 * @throws Throwable the error
	 */
	private IResult process(final Integer since) throws Exception {
		final UserService service = UserService.getInstance();
		final Map<String,Serializable> properties = new HashMap<String,Serializable>();
		final IApplicationContext context = service.authentication(properties);

		service.signOut(context);

		return IVisitor.SUCCESS;
	}

	/*
	 * See super class or interface. (non-Javadoc)
	 * @see org.infodavid.common.util.IVisitor#visit(java.lang.Object)
	 */
	@TransactionAttribute(TransactionAttributeType.NOT_SUPPORTED)
	public IResult visit(final IScheduledCommand cmd) throws Exception {
		final IResult result = process(UserService.getInstance().getSessionIdleTimeInMin());
		// we schedule next fire time, this takes in account a change of session idle time
		final DateTime nextScheduleDate =
		    new DateTime().plusMinutes(UserSessionDataService.getInstance().getSessionIdleTimeInMin());

		SchedulerService.getInstance().reschedule(nextScheduleDate, cmd);

		return result;
	}

	/*
	 * (non-Javadoc)
	 * @see org.infodavid.common.tasks.ITask#initialize()
	 */
	@TransactionAttribute(TransactionAttributeType.NOT_SUPPORTED)
	public void initialize() throws Exception {
		process(null);
	}
}
